﻿/*****************************************
 * 
 *  copyright (c) by ylshen
 * 
 *  author : ylshen (syl.lucky@gmail.com)
 * 
 **************************************** */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace JYStockAnalyser.WinUI
{
    /// <summary>
    /// 系统参数管理器
    /// </summary>
    public class ParametersManager
    {
        public const string PARAM_USERNAME = "UserName";

        static string GetParametersFilePath()
        {
            return System.Configuration.ConfigurationManager.AppSettings["paramsFile"];
        }

        /// <summary>
        /// 获取一个参数的值
        /// </summary>
        /// <param name="param">参数名称</param>
        /// <returns></returns>
        public static string GetParameterValue(string param)
        {
            m_ensureFileExists();

            Dictionary<string, string> parameters = m_getParameters();

            if (!parameters.ContainsKey(param))
            {
                SetParameterValue(param, string.Empty);
                return string.Empty;
            }
            else
            {
                return parameters[param];
            }
        }

        /// <summary>
        /// 设置一个参数的值
        /// </summary>
        /// <param name="param">参数名称</param>
        /// <param name="Value">参数值</param>
        public static void SetParameterValue(string param, string Value)
        {
            m_ensureFileExists();

            Dictionary<string, string> parameters = m_getParameters();
            if (!parameters.ContainsKey(param))
            {
                parameters.Add(param, Value);
            }
            else
            {
                parameters[param] = Value;
            }
           
            StreamWriter sw = new StreamWriter(GetParametersFilePath());
            DictionaryXmlSerializer.Serialize(sw, parameters);         
            sw.Close();
        }    

        private static Dictionary<string, string> m_getParameters()
        {            
            Dictionary<string, string> dics = new Dictionary<string,string>();
            StreamReader sr = new StreamReader(GetParametersFilePath());
            DictionaryXmlSerializer.Deserialize(sr, dics);
            sr.Close();
            return dics;           
        }

        /// <summary>
        /// 确定参数文件的存在，若不存在则创建它
        /// </summary>
        private static void m_ensureFileExists()
        {
            if (!File.Exists(GetParametersFilePath())) { File.Create(GetParametersFilePath()); }
        }
    }
}
